//导入express包
var express = require('express');
//创建路由对象
var router = express.Router();

//导入数据库操作
const { getAll, getById, exec } = require('../db/index.js');
//编写路由
/* 
获取所有计划
GET/todo
*/
router.get('/', async (req, res) => {
  //1.解析请求参数
  //2.编写sql语句
  const sql = `select * from todo`;
  //3.执行sql语句返回结果
  const data = await getAll(sql);
  res.send(data);
});

/* 
根据id获取计划
GET/todo/：id
*/
router.get('/:id', async (req, res) => {
  const id = req.params.id;
  const sql = `select * from todo where id=${id}`;
  const data = await getById(sql);
  res.send(data);
});

/* 
根据post新增计划
POST/todo
*/
/* 
post新增用户{"content": " 7:30半闹钟  早起朗读课文","status": 0}
POST/todo
*/
router.post('/', async (req, res) => {
  const { content, status } = req.body;
  console.log(req.body);
  const sql = `insert into todo(content,status) values('${content}','${status}')`;
  //3.执行sql语句
  const data = await exec(sql);
  res.send({
    id: data.insertId,
    content: content,
    status: status,
  });
});

/* 
put修改计划
PUT/users/:id
*/
router.put('/:id', async (req, res) => {
  //1.解析请求数据
  const id = req.params.id;
  //2.对象解构
  const { content, status } = req.body;
  //3.编写sql语句
  const sql = `update todo set content='${content}',status=${status} where id=${id}`;
  //4.执行sql语句
  const data = await exec(sql);
  res.send({
    id: id,
    content: content,
    status: status,
  });
});

/* 
delete删除计划
DELETE/users/:id
*/
router.delete('/:id', async (req, res) => {
  //1.解析请求数据
  const id = req.params.id;
  //2.编写sql语句
  const sql = `delete from todo where id=${id}`;
  //3.执行sql语句
  const data = await exec(sql);
  res.status(204).send('');
});
module.exports = router;
